package com.app.business.web.business;

import com.app.business.model.AzProject;
import com.app.business.model.StorageRoom;
import com.app.business.service.AzProjectService;
import com.app.business.service.StorageRoomService;
import com.app.system.jpa.PageBean;
import com.app.system.log4j2.LogUtils;
import com.app.system.permission.model.DataDict;
import com.app.system.permission.service.DataDictService;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.ParamUtils;
import com.app.system.utils.WebUtils;
import com.app.system.utils.dataType.BigDecimalUtils;
import com.app.system.utils.dataType.DateUtils;
import com.app.system.utils.dataType.IntegerUtils;
import com.app.system.utils.dataType.StringUtils;
import com.app.system.utils.exception.Precondition;
import com.app.system.utils.exception.Response;
import com.app.system.utils.page.LayUiUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import freemarker.template.Configuration;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;
import java.util.*;

/**
 * 储物间管理
 * Created by lsh on 2019/2/11 14:49.
 * @author lsh
 */
@Controller
@RequestMapping("/business/storageRoom/*")
public class StorageRoomController {

    @Resource
    private StorageRoomService storageRoomService;
    @Resource
    private DataDictService dataDictService;
    @Resource
    private AzProjectService azProjectService;
    private Logger logger = LogUtils.getBusinessLogger();

    @Autowired
    private Configuration freemarkerConfiguration; // 注入bean，这里是属性注入，推荐构造注入
    /**
     * 住宅房源数据管理列表
     */
    @RequestMapping("storageRoomList")
    @RequiresPermissions("storageRoom:storageRoomList")
    public void storageRoomList(HttpServletRequest request, ModelMap modelMap) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        AzProject azProject = this.azProjectService.findOne(projectId);
        modelMap.addAttribute("azProject", azProject);
    }

    /**
     * 加载房源信息数据
     *
     * @return
     */
    @RequestMapping("loadStorageRoomList")
    @ResponseBody
    @RequiresPermissions("storageRoom:loadStorageRoomList")
    public Map loadStorageRoomList(HttpServletRequest request) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        List<Map> listData = Lists.newArrayList();
        PageBean<StorageRoom> storageRoomPageBean = this.storageRoomService.storageRoomListByProjectId(projectId);
        List<StorageRoom> storageRoomList = storageRoomPageBean.getDatas();
        Map<String, DataDict> houseStatusMap = this.dataDictService.getMapByParentNameForValue("房源状态");
        if (!CollectionUtils.isEmpty(storageRoomList)) {
            Map<String, Object> item = null;
            for (StorageRoom storageRoom : storageRoomList) {
                item = null;
                item = Maps.newHashMap();
                item.put("id", storageRoom.getId());
                item.put("buildNum", StringUtils.getNotNull(storageRoom.getBuildNum()));
                item.put("houseNum", StringUtils.getNotNull(storageRoom.getHouseNum()));
                item.put("floor", IntegerUtils.getNotNull(storageRoom.getFloor()));
                item.put("buildArea", BigDecimalUtils.getNotNullStr(storageRoom.getBuildArea()));
                item.put("houseStatus", storageRoom.getHouseStatus());
                item.put("houseStatusStr", StringUtils.dataDictShow(houseStatusMap.get(storageRoom.getHouseStatus().toString())));
                item.put("chooseHouseDate", DateUtils.dateToStringDefault(storageRoom.getChooseHouseDate()));
                item.put("memo", storageRoom.getMemo());
                listData.add(item);
            }
        }
        return LayUiUtils.page(storageRoomPageBean.getTotalCount().intValue(), listData);
    }

    /**
     * 储物间信息导出
     */
    @RequestMapping("storageRoomListExcel")
    @RequiresPermissions("storageRoom:storageRoomListExcel")
    public void storageRoomListExcel(HttpServletRequest request, HttpServletResponse response) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        PageBean<StorageRoom> storageRoomPageBean = this.storageRoomService.storageRoomExcelListByProjectId(projectId);
        List<StorageRoom> storageRoomList = storageRoomPageBean.getDatas();
        Map<String, DataDict> houseStatusMap = this.dataDictService.getMapByParentNameForValue("房源状态");
        try {
            // 封装导出数据
            Map data = Maps.newHashMap();
            data.put("storageRoomList", storageRoomList);
            data.put("houseStatusMap", houseStatusMap);
            data.put("exportPerson", SecurityUtils.getSubject().getPrincipal());   //导出人姓名
            data.put("exportTime", DateUtils.dateToStringFormat(new Date(), "yyyy-MM-dd HH:mm:ss"));   //导出时间
//            data.put("decisions", exportDecisionList); //第二个worksheet的数据对象
            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/x-download;");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(("储物间数据导出.xls").getBytes(), "iso-8859-1"));
            freemarkerConfiguration.getTemplate("/business/storageRoom/storageRoomListExcel.ftl").process(data, response.getWriter());
        } catch (Exception e) {
            logger.error("文件下载异常", e);
            e.printStackTrace();
        }
    }

    /**
     * 储物间房源管理
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("storageRoomForm")
    @RequiresPermissions("storageRoom:storageRoomForm")
    public void storageRoomForm(HttpServletRequest request, ModelMap modelMap) {
        Integer storageRoomId = ParamUtils.getInt(request, "storageRoomId", 0);
        Integer azProjectId = ParamUtils.getInt(request, "azProjectId", 0);

        StorageRoom storageRoom = this.storageRoomService.findOne(storageRoomId);
        AzProject azProject = azProjectService.findOne(azProjectId);
        storageRoom = storageRoom == null ? new StorageRoom() : storageRoom;
        Precondition.checkSqdsArguement(azProject != null, "找不到所属安置项目！");

        modelMap.addAttribute("storageRoom", storageRoom);
        modelMap.addAttribute("azProject", azProject);
    }


    /**
     * 房源信息保存
     *
     * @param request
     * @return
     */
    @RequestMapping("storageRoomSave")
    @ResponseBody
    @RequiresPermissions("storageRoom:storageRoomSave")
    public Response storageRoomSave(HttpServletRequest request) {
        Integer storageRoomId = ParamUtils.getInt(request, "storageRoomId", 0);
        Integer azProjectId = ParamUtils.getInt(request, "azProjectId", 0);
        StorageRoom storageRoom = storageRoomService.findOne(storageRoomId);
        AzProject project = azProjectService.findOne(azProjectId);
        Precondition.checkAjaxArguement(project != null, "0012", "项目不存在");

        if (storageRoom == null) {
            storageRoom = new StorageRoom();
        }
        Precondition.checkAjaxArguement(storageRoom.getHouseStatus() == null || !storageRoom.getHouseStatus().equals(2), "0011", "储物间已选，不能修改");
        WebUtils.bind(request, storageRoom);
        storageRoom.setAzProject(project);
        storageRoomService.save(storageRoom);

        Response response = new Response();
        response.setCode("0001");
        response.setData(project.getId());
        return response;
    }


    /**
     * 删除住宅房源
     *
     * @param request
     * @return
     */
    @RequestMapping("deleteStorageRoom")
    @ResponseBody
    @RequiresPermissions("storageRoom:deleteStorageRoom")
    public Response deleteStorageRoom(HttpServletRequest request) {
        Integer storageRoomId = ParamUtils.getInt(request, "storageRoomId", 0);
        StorageRoom storageRoom = storageRoomService.findOne(storageRoomId);
        Precondition.checkAjaxArguement(storageRoom != null, "1111", "数据错误！");
        Precondition.checkAjaxArguement(storageRoom.getHouseStatus() != null && storageRoom.getHouseStatus() != 2, "1111", "房源已选择，不可删除！");
        this.storageRoomService.delete(storageRoom.getId());
        return new Response("0001", "操作成功");
    }

    /**
     * 导入页面
     *
     * @param request
     * @param modelMap
     */
    @RequestMapping("importPage")
    @RequiresPermissions("storageRoom:importPage")
    public void importPage(HttpServletRequest request, ModelMap modelMap) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        AzProject azProject = this.azProjectService.findOne(projectId);
        Precondition.checkAjaxArguement(azProject != null, "9999", "导入的安置项目不存在");
        modelMap.addAttribute("azProject", azProject);
    }


    /**
     * 导入储物室数据
     *
     * @param request
     * @return
     * @throws Exception
     */
    @Transactional
    @RequestMapping("importStorageRoom")
    @ResponseBody
    @RequiresPermissions("storageRoom:importStorageRoom")
    public Response importStorageRoom(HttpServletRequest request) {
        Integer projectId = ParamUtils.getInt(request, "azProjectId", 0);
        AzProject azProject = this.azProjectService.findOne(projectId);
        Precondition.checkAjaxArguement(azProject != null, "9999", "导入的安置项目不存在");

        String storageRooms = request.getParameter("storageRoomArray");
        String[] storageRoomArray = storageRooms.split("\r\n");

        //Set<安置项目-幢号-户号-所在层数>
        Set<String> storageRoomSet = this.storageRoomService.findStorageRoomSetByAzProjectId(azProject.getId());

        //buildNum:幢号，houseNum:户号，floor：所在层数，buildArea：建筑面积，memo：备注
        String buildNum = null, houseNum = null, floor = null, buildArea = null,poolArea = null, memo = null;

        StorageRoom storageRoom = null;
        //待导入的房源数据
        List<StorageRoom> importStorageRoomList = new ArrayList<>();

        String[] rowObj = null;
        String excelStorage = null;
        int rowObjLength = 0;//每条数据的列数
        int errorCount = 0;//错误数据数量
        StringBuffer msg = new StringBuffer();
        int index = 0;
        for (String storageRoomInfo : storageRoomArray) {
            rowObj = null;
            rowObj = storageRoomInfo.split("\t");
            rowObjLength = rowObj.length;
            Precondition.checkAjaxArguement(rowObjLength == 6, "0012", "请确认每列都有数据！");
            if (rowObj.length == 0) {
                continue;
            }

            index = 0;
            buildNum = rowObj[index]; //幢号
            index++;
            houseNum = rowObj[index]; //户号
            index++;
            floor = rowObj[index]; //所在层数
            index++;
            buildArea = rowObj[index]; //建筑面积
            index++;
            poolArea = rowObj[index]; //公摊面积
            index++;
            memo = rowObj[index];//备注

            excelStorage = projectId + "-" + buildNum + "-" + houseNum + "-" + floor;

            if (StringUtils.isEmpty(excelStorage)) {
                continue;
            }
            //只导入不存在的房源
            if (storageRoomSet.contains(excelStorage)) {
                errorCount++;
                msg.append("<br/>" + storageRoomInfo + ",");
                //已经存在的数据输出到页面
                continue;
            }

            storageRoom = new StorageRoom();
            storageRoom.setHouseStatus(1);
            storageRoom.setAzProject(azProject);
            storageRoom.setBuildNum(buildNum);
            storageRoom.setHouseNum(houseNum);
            storageRoom.setFloor(Integer.valueOf(floor));
            storageRoom.setBuildArea(BigDecimalUtils.stringToBigDecimal(buildArea));
            storageRoom.setPoolArea(BigDecimalUtils.stringToBigDecimal(poolArea));
            storageRoom.setMemo(memo);

            importStorageRoomList.add(storageRoom);
        }
        this.storageRoomService.batchSave(importStorageRoomList);
        String successInfo = "插入" + importStorageRoomList.size() + "条数据;";
        if (errorCount > 0) {
            successInfo = successInfo + "失败" + errorCount + "条，如下：";
        }
        msg = msg.length() == 0 ? msg : msg.replace(0, msg.length(), msg.toString()).append("<br/>数据已存在，无法导入");
        System.out.println(successInfo + msg.toString());
        Response response = new Response("0001", successInfo + msg.toString());
        return response;
    }

}
